<template>
  <div class="page_container !bg-white px-10 relative">
    <!-- <img class="w-16 h-16 mx-auto mt-[88px]" src="@assets/images/logo.png" alt="">
        <div class=" text-lg font-semibold mx-auto text-primary">{{ $t('welcome') }}</div>

        <van-form @submit="onSubmit" class="mt-[76px]">
          <div>
            <div class="text-sm mb-1 text-sub-text">{{ $t('cellphone') }}</div>
            <div class="border border-gap-text rounded-lg flex items-center">
              <div class="flex items-center border-r border-gap-text px-3" @click="showAreaCode = true">
                <span class="mr-1">{{ formData.areaCode }}</span>
                <van-icon name="arrow-down" />
              </div>
              <van-field class="!py-1 !text-base" clearable v-model="formData.phoneNumber" name="phoneNumber" type="number"
                :placeholder="$t('placeholder.inputPhoneNumber')" />
            </div>
          </div>

          <div class="mt-5" v-if="isByPassword">
            <div class="text-sm mb-1 text-sub-text">{{ $t('password') }}</div>
            <div class="border border-gap-text rounded-lg">
              <van-field class="!py-1" clearable v-model="formData.password" name="password" type="password"
                :placeholder="$t('placeholder.inputPassword')" />
            </div>
          </div>

          <div class="mt-5" v-else>
            <div class="text-sm mb-1 text-sub-text">{{ $t('reAcquireDesc') }}</div>
            <div class="border border-gap-text rounded-lg">
              <van-field class="!py-1" clearable v-model="formData.verificationCode" name="verificationCode" type="text"
                :placeholder="$t('placeholder.inputVerificationCode')">
                <template #button>
                  <span class="text-primary" @click="reSend" v-if="count <= 0">{{ $t('buttons.verificationCode') }}</span>
                  <span class="text-primary" v-else>{{ count }}S</span>
                </template>
</van-field>
</div>
</div>

<div class="mt-16">
  <van-button :loading="loading" :disabled="!(formData.phoneNumber && formData.password)" block type="primary"
    native-type="submit">
    {{ $t('buttons.login') }}
  </van-button>
</div>
</van-form>

<div class="text-xs absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col w-[300px] items-center">
  <div class="flex flex-row text-primary">
    <div class="text-sub-text">{{ $t('notHaveAccount') }}</div>
    <div @click="getCode(true)">{{ $t('nowRegister') }}</div>
  </div>
  <div class="text-sub-text">{{ version }}</div>
</div>

<van-popup v-model:show="showAreaCode" round position="bottom">
  <van-picker :columns="countryCode" @cancel="showAreaCode = false" @confirm="onConfirmAreaCode"
    :columns-field-names="{ text: 'phone_code', value: 'phone_code', children: 'children' }" />
</van-popup> -->

  </div>
</template>

<script setup lang='ts'>
import md5 from 'md5';
import type { PickerConfirmEventParams, } from 'vant';
import { login, sendSms } from '@/api/login';
import { getAdminUserInfo,getImLogin,getinviteeUserInfo, } from '@/api/im';
import { searchUserInfoByBusiness } from "@/api/user";
import countryCode from '@/utils/areaCode'
import { feedbackToast } from '@/utils/common';
import { setIMProfile, setAdminToken } from '@/utils/storage';
import { UsedFor } from '@/api/data';
import { onMounted } from 'vue';
import { SessionType } from "@openim/wasm-client-sdk";
import useConversationStore from "@store/modules/conversation";
import useSendMessage from '@/hooks/useSendMessage';
import useCreateNomalMessage from "@pages/conversation/chat/components/ChatFooter/useCreateNomalMessage";
const conversationStore = useConversationStore();
const { sendMessage } = useSendMessage();
import { IMSDK,initStore } from "@/utils/imCommon";
import useContactStore from "@/store/modules/contact";
import {getIMToken, getIMUserID} from "@/utils/storage";
const version = process.env.VERSION
const messageContent = ref('')
const { switchNomalMessage } = useCreateNomalMessage({
  messageContent,
});
import useConversationToggle from '@/hooks/useConversationToggle';
const { toSpecifiedConversation } = useConversationToggle();
const { t } = useI18n()
const router = useRouter();
const contactStore = useContactStore();
const formData = reactive({
  phoneNumber: localStorage.getItem("IMAccount") ?? '',
  areaCode: '+86',
  password: '',
  verificationCode: '',
  accept: true
})
const loading = ref(false)
const isByPassword = ref(true)
const showAreaCode = ref(false)
const count = ref(0)
let timer: NodeJS.Timer


const onSubmit = async () => {
  loading.value = true
  localStorage.setItem("IMAccount", formData.phoneNumber)
  try {
    const { data: { chatToken, imToken, userID } } = await login({
      phoneNumber: formData.phoneNumber,
      password: md5(formData.password),
      areaCode: formData.areaCode
    })

    setIMProfile({ chatToken, imToken, userID })
    router.push('/conversation')
  } catch (error) {
    feedbackToast({ message: t('messageTip.loginFailed'), error })
  }
  loading.value = false
}

const onConfirmAreaCode = ({ selectedValues }: PickerConfirmEventParams) => {
  formData.areaCode = String(selectedValues[0])
  showAreaCode.value = false
}

const reSend = () => {
  if (count.value > 0) return
  sendSms({
    phoneNumber: formData.phoneNumber,
    areaCode: formData.areaCode,
    usedFor: UsedFor.Login
  })
    .then(startTimer)
    .catch(error => feedbackToast({ message: t('messageTip.sendCodeFailed'), error }))
}

const startTimer = () => {
  if (timer) {
    clearInterval(timer)
  }
  count.value = 60
  timer = setInterval(() => {
    if (count.value > 0) {
      count.value -= 1
    } else {
      clearInterval(timer)
    }
  }, 1000)
}

const getCode = (flag: boolean) => {
  router.push({
    path: 'getCode',
    query: {
      isRegiste: flag + ''
    }
  })
}

const searchUsers = async (value: string) => {
  try {
    const { data: { users, total } } = await searchUserInfoByBusiness(value);
    console.log("zsq-total", total)
    console.log("zsq-users", users)
    const businessData = users[0];
    console.log("zsq-businessData", )
    console.log("zsq-userID", [businessData.userID])
    const { data } = await IMSDK.getUsersInfo([businessData.userID]);
    const imData = data[0]?.friendInfo ?? data[0]?.publicInfo ?? {};
    const info = {
      ...imData,
      ...businessData,
    };
    console.log("zsq-info", info)
    contactStore.setUserCardData({
      baseInfo: info,
    });
    toConversation()
  } catch (error) { }
};


const loginCheck = () => {
    const IMToken = getIMToken()
    const IMUserID = getIMUserID()
    if (!IMToken || !IMUserID) {
        router.push('/login');
        return;
    }
    tryLogin();
};

const tryLogin = async () => {
    const IMToken = getIMToken();
    const IMUserID = getIMUserID();
    console.log("zsq-IMToken", IMToken)
    console.log("zsq-IMUserID", IMUserID)
    try {
        await IMSDK.login({
            userID: IMUserID!,
            token: IMToken!,
            apiAddr: process.env.API_URL!,
            wsAddr: process.env.WS_URL!,
            platformID: 5,
        })
        initStore();
    } catch (error) {
        router.push('/login');
    }
}

const toConversation = () => {
  console.log("zsq-contactStore", contactStore.storeUserCardData.baseInfo?.userID!)
  toSpecifiedConversation({
    sourceID: contactStore.storeUserCardData.baseInfo?.userID!,
    sessionType: SessionType.Single
  })
}

// 从 URL 获取参数并触发登录
const autoLogin = async () => {
  // const { inviterUserID, imToken, chatToken, inviteeUserID, chatType } = router.currentRoute.value.query;
  // console.log("inviterUserID", inviterUserID)
  // console.log("imToken", imToken)
  // console.log("chatToken", chatToken)
  // console.log("inviteeUserID", inviteeUserID)
  // console.log("chatType", chatType)
  const { token, inviteeUserID, chatType, groupID } = router.currentRoute.value.query;
  // if (inviterUserID && typeof inviterUserID === 'string' && typeof imToken === 'string') {
  if (token && typeof token === 'string' && (typeof inviteeUserID === 'string' || typeof groupID === 'string')) {
    try {
      // console.log("inviterUserID", inviterUserID)
      // console.log("imToken", imToken)
      // console.log("chatToken", chatToken)
      console.log("token", decodeURIComponent(token))
      console.log("inviteeUserID", inviteeUserID)
      console.log("chatType", chatType)
      console.log("groupID", groupID)
      // const { data: { chatToken, imToken, userID } } = await chatAdminLogin(
      //   phoneNumber,
      //   md5(password)
      // )
      // searchUsers(conversationID.split('_')[1])
      const adminToken = decodeURIComponent(token);
      setAdminToken(adminToken)
      const userInfo =  await getAdminUserInfo();
      const imInfo = await getImLogin();
      
      const ext  = JSON.parse(userInfo.data.ext)
      console.log("zsq-userInfo", ext)
      console.log("zsq-imInfo", imInfo)

      const userID =ext.im_id
      const chatToken = imInfo.data.chatToken 
      const imToken = imInfo.data.imToken
      let conversationID = ""

      setIMProfile({ chatToken, imToken, userID, chatType, adminToken})

      // debugger
      if (inviteeUserID !== null && inviteeUserID !== undefined) {
        const inviteeUserInfo = await getinviteeUserInfo(inviteeUserID)
        const inviteeUserInfoExt = JSON.parse(inviteeUserInfo.data.ext)
        console.log("zsq-inviteeUserInfo", inviteeUserInfoExt.im_id)
        conversationID =  "si_" + inviteeUserInfoExt.im_id + "_" + userID
      } else if (groupID !== null && groupID !== undefined) { conversationID = "sg_" + groupID}
      console.log("zsq-conversationID", conversationID)
      router.push('/conversation?conversationID=' + conversationID)
    } catch (error) {
      feedbackToast({ message: t('messageTip.loginFailed'), error })
    }
    loading.value = false
  } else {
    console.warn("缺少登录参数");
  }
}

onMounted(() => {
  autoLogin()
})

</script>

<style lang='scss' scoped>
.page_container {
  background: linear-gradient(180deg, rgba(0, 137, 255, 0.1) 0%, rgba(255, 255, 255, 0) 100%);
}
</style>
